package net.wwang.open.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    //允许基于选择匹配在资源级配置基于网络的安全性
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许druid监控
        http.csrf().ignoringAntMatchers("/druid/*","/swagger-ui.html");
        http.headers().contentTypeOptions().disable();
        http
                //请求管理
                .authorizeRequests()
                .antMatchers("/**").permitAll()
                .and().formLogin()
                .loginPage("/index.html")// 登录跳转 URL
                .loginProcessingUrl("/login")// 处理表单登录 URL
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(myAuthenticationSuccessHandler) //登录成功页面跳转的处理器
                .failureHandler(myAuthenticationFailureHandler);//登录失败页面跳转的处理器
        //允许跨站资源共享
        http.cors().disable();
        //允许跨站请求伪造
        http.csrf().disable();
    }

    /**
     * 设置登入密码加密格式
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
